﻿<!DOCTYPE HTML>
<html>

<head>
   <title>动态创建表格</title>
   <meta charset="utf-8" />
   <style>
      table {
         width: 600px;
         border-collapse: collapse;
         text-align: center;
      }

      td,
      th {
         border: 1px solid #ccc
      }
   </style>

</head>

<body>
   <div>创建元素 document.createElement("elem") </div>
   <div>创建注释 document.createComment("~~~~");</div>
   <div>创建文本 document.createTextNode("~~~");</div>
   <div>创建文本片段 document.createDocumentFragment()</div>
   <div id="data">
      <table>
         <thead>
            <tr></tr>
         </thead>
      </table>

   </div>

   <script>
      var table = document.querySelector("#data>table");
      var json = [{
            "ename": "Tom",
            "salary": 11000,
            "age": 25
         },
         {
            "ename": "John",
            "salary": 13000,
            "age": 28
         },
         {
            "ename": "Mary",
            "salary": 12000,
            "age": 25
         }
      ];


      //优化,创建文档片段
      var frag = document.createDocumentFragment();
      for (var key in json[0]) {
         //添加元素节点
         var th = document.createElement("th");
         frag.appendChild(th);
         //方法1
         // th.innerHTML = key;
         //方法2 创建文本节点
         var text = document.createTextNode(key);
         th.appendChild(text);
      }

      //不要一直用tr 一直添加元素,影响效率,使用fragment
      var tr = document.querySelector("#data thead>tr");
      tr.appendChild(frag);

      var tbody = document.createElement("tbody");
      for (var i = 0; i < json.length; i++) {
         var emp = json[i];
         console.log(emp);
         var tr = document.createElement("tr");
         console.log(emp);

         tbody.appendChild(tr);
         for (var key in emp) {
            var td = document.createElement("td");
            td.appendChild(document.createTextNode(emp[key]));
            tr.appendChild(td);
         }

      }

      table.appendChild(tbody);


      //添加注释节点
      // var comment = document.createComment("this is th");
      // tr.appendChild(comment);
   </script>
</body>

</html>